package com.basic.business.storeIndicators.controller;


import com.basic.business.indicatorsFile.domain.TIndicatorsFile;
import com.basic.business.indicatorsFile.service.ITIndicatorsFileService;
import com.basic.business.storeIndicators.domain.TStoreIndicators;
import com.basic.business.storeIndicators.dto.TStoreIndicatorsDto;
import com.basic.business.storeIndicators.service.ITStoreIndicatorsService;
import com.basic.common.annotation.FileExport;
import com.basic.common.annotation.Log;
import com.basic.common.config.BasicConfig;
import com.basic.common.core.controller.BaseController;
import com.basic.common.core.domain.AjaxResult;
import com.basic.common.core.page.TableDataInfo;
import com.basic.common.enums.BusinessType;
import com.basic.common.exception.file.InvalidExtensionException;
import com.basic.common.utils.SecurityUtils;
import com.basic.common.utils.easyExcel.EasyExcelUtils;
import com.basic.common.utils.file.FileUploadUtils;
import com.basic.common.utils.file.MimeTypeUtils;
import com.basic.common.utils.poi.ExcelUtil;
import org.apache.logging.log4j.util.Strings;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 店铺指标数据Controller
 *
 * @author zhaoxy_jn@163.com
 */
@RestController
@RequestMapping("/business/storeIndicators")
public class TStoreIndicatorsController extends BaseController
{
    @Resource
    private ITStoreIndicatorsService tStoreIndicatorsService;

    @Resource
    private ITIndicatorsFileService tIndicatorsFileService;

    /**
     * 查询店铺指标数据列表
     */
    @PreAuthorize("@ss.hasPermi('business:storeIndicators:list')")
    @GetMapping("/list")
    public TableDataInfo list(TStoreIndicators tStoreIndicators)
    {
        startPage();
        List<TStoreIndicators> list = tStoreIndicatorsService.searchList(tStoreIndicators);
        return getDataTable(list);
    }

    /**
     * 查询店铺指标数据列表(不分页)
     */
    @GetMapping("/allList")
    public AjaxResult allList(TStoreIndicators tStoreIndicators)
    {
        List<TStoreIndicators> list = tStoreIndicatorsService.searchList(tStoreIndicators);
        return AjaxResult.success(list);
    }

    /**
     * 导出店铺指标数据列表
     */
    @PreAuthorize("@ss.hasPermi('business:storeIndicators:export')")
    @Log(title = "店铺指标数据", businessType = BusinessType.EXPORT)
    @FileExport(fileName = "店铺指标数据.xlsx")
    @PostMapping("/export")
    public String export(TStoreIndicators tStoreIndicators) throws IOException
    {
        List<TStoreIndicators> list = tStoreIndicatorsService.getList(tStoreIndicators);
        return EasyExcelUtils.excelExport(TStoreIndicators.class,"店铺指标数据数据", list);
    }

    /**
     * 获取店铺指标数据详细信息
     */
    @PreAuthorize("@ss.hasPermi('business:storeIndicators:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id)
    {
        return success(tStoreIndicatorsService.get(id));
    }

    /**
     * 新增店铺指标数据
     */
    @PreAuthorize("@ss.hasPermi('business:storeIndicators:add')")
    @Log(title = "店铺指标数据", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TStoreIndicators tStoreIndicators)
    {
        return toAjax(tStoreIndicatorsService.insert(tStoreIndicators));
    }

    /**
     * 修改店铺指标数据
     */
    @PreAuthorize("@ss.hasPermi('business:storeIndicators:edit')")
    @Log(title = "店铺指标数据", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TStoreIndicators tStoreIndicators)
    {
        return toAjax(tStoreIndicatorsService.update(tStoreIndicators));
    }

    /**
     * 删除店铺指标数据
     */
    @PreAuthorize("@ss.hasPermi('business:storeIndicators:remove')")
    @Log(title = "店铺指标数据", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids)
    {
        return toAjax(tStoreIndicatorsService.deleteByIds(ids));
    }

    /**
     * 上传店铺指标数据
     * @param file
     * @return
     */
    @PostMapping("/uploadData")
    public AjaxResult uploadData(MultipartFile file,String storeId,Date selectDate,String fileHash) {


        String username = SecurityUtils.getUsername();

        //上传路径
        String absolutePath = null;
        try {
            absolutePath = FileUploadUtils.upload(BasicConfig.getIndicatorsPath(), file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION);
        } catch (InvalidExtensionException | IOException e) {
            throw new RuntimeException(e);
        }

        //组装文件上传记录数据并存储
        TIndicatorsFile tIndicatorsFile = new TIndicatorsFile();
        tIndicatorsFile.setId(null);
        tIndicatorsFile.setStoreId(storeId);
        tIndicatorsFile.setFileName(file.getOriginalFilename());
        tIndicatorsFile.setSelectDate(selectDate);
        tIndicatorsFile.setAbsolutePath(absolutePath);
        tIndicatorsFile.setFileHash(fileHash);
        tIndicatorsFile.setType(1);
        tIndicatorsFile.setCreateBy(username);
        tIndicatorsFile.setCreateTime(new Date());

        tIndicatorsFileService.insert(tIndicatorsFile);


        ExcelUtil<TStoreIndicatorsDto> util = new ExcelUtil<TStoreIndicatorsDto>(TStoreIndicatorsDto.class);
        try {
            List<TStoreIndicatorsDto> list = util.importExcel(file.getInputStream(),5);

            List<Date> statDateList=new ArrayList<>();

            List<TStoreIndicators> saveList = new ArrayList<>();

            list.forEach(item->{
                TStoreIndicators tStoreIndicators = new TStoreIndicators();
                tStoreIndicators.setId(null);
                tStoreIndicators.setStoreId(storeId);
                tStoreIndicators.setFileId(tIndicatorsFile.getId());
                tStoreIndicators.setStatDate(item.getStatDate());
                tStoreIndicators.setSuccessGoodsRefundAmount(Strings.isBlank(item.getSuccessGoodsRefundAmount().replace(",",""))?null:new BigDecimal(item.getSuccessGoodsRefundAmount().replace(",","")));
                tStoreIndicators.setPayAmount(Strings.isBlank(item.getPayAmount().replace(",",""))?null:new BigDecimal(item.getPayAmount().replace(",","")));
                tStoreIndicators.setStagesPayAmount(Strings.isBlank(item.getStagesPayAmount().replace(",",""))?null:new BigDecimal(item.getStagesPayAmount().replace(",","")));
                tStoreIndicators.setPayQuantity(Strings.isBlank(item.getPayQuantity().replace(",",""))?null:Integer.valueOf(item.getPayQuantity().replace(",","")));
                tStoreIndicators.setGoodsAddPeopleNumber(Strings.isBlank(item.getGoodsAddPeopleNumber().replace(",",""))?null:Integer.valueOf(item.getGoodsAddPeopleNumber().replace(",","")));
                tStoreIndicators.setGoodsAddQuantity(Strings.isBlank(item.getGoodsAddQuantity().replace(",",""))?null:Integer.valueOf(item.getGoodsAddQuantity().replace(",","")));
                tStoreIndicators.setGoodsPageViewNumber(Strings.isBlank(item.getGoodsPageViewNumber().replace(",",""))?null:Integer.valueOf(item.getGoodsPageViewNumber().replace(",","")));
                tStoreIndicators.setGoodsVisitorNumber(Strings.isBlank(item.getGoodsVisitorNumber().replace(",",""))?null:Integer.valueOf(item.getGoodsVisitorNumber().replace(",","")));
                tStoreIndicators.setGoodsDetailVisitorNumber(Strings.isBlank(item.getGoodsDetailVisitorNumber().replace(",",""))?null:Integer.valueOf(item.getGoodsDetailVisitorNumber().replace(",","")));
                tStoreIndicators.setGoodsCollectPeopleNumber(Strings.isBlank(item.getGoodsCollectPeopleNumber().replace(",",""))?null:Integer.valueOf(item.getGoodsCollectPeopleNumber().replace(",","")));
                tStoreIndicators.setGoodsStopDuration(Strings.isBlank(item.getGoodsStopDuration().replace(",",""))?null:Integer.valueOf(item.getGoodsStopDuration().replace(",","")));
                tStoreIndicators.setPlaceOrderBuyNumber(Strings.isBlank(item.getPlaceOrderBuyNumber().replace(",",""))?null:Integer.valueOf(item.getPlaceOrderBuyNumber().replace(",","")));
                tStoreIndicators.setPayBuyNumber(Strings.isBlank(item.getPayBuyNumber().replace(",",""))?null:Integer.valueOf(item.getPayBuyNumber().replace(",","")));
                tStoreIndicators.setPlaceOrderConversionRate(item.getPlaceOrderConversionRate());
                tStoreIndicators.setGoodsDetailDapRate(item.getGoodsDetailDapRate());
                tStoreIndicators.setPlaceOrderAmount(Strings.isBlank(item.getPlaceOrderAmount().replace(",",""))?null:new BigDecimal(item.getPlaceOrderAmount().replace(",","")));
                tStoreIndicators.setCollectConversionRate(item.getCollectConversionRate());
                tStoreIndicators.setAddPurchaseConversionRate(item.getAddPurchaseConversionRate());
                tStoreIndicators.setPayOldBuyNumber(Strings.isBlank(item.getPayOldBuyNumber().replace(",",""))?null:Integer.valueOf(item.getPayOldBuyNumber().replace(",","")));
                tStoreIndicators.setOldBuyPayAmount(Strings.isBlank(item.getOldBuyPayAmount().replace(",",""))?null:new BigDecimal(item.getOldBuyPayAmount().replace(",","")));
                tStoreIndicators.setPayConversionRate(item.getPayConversionRate());
                tStoreIndicators.setPayNewBuyNumber(Strings.isBlank(item.getPayNewBuyNumber().replace(",",""))?null:Integer.valueOf(item.getPayNewBuyNumber().replace(",","")));
                tStoreIndicators.setHavePayGoodsNumber(Strings.isBlank(item.getHavePayGoodsNumber().replace(",",""))?null:Integer.valueOf(item.getHavePayGoodsNumber().replace(",","")));
                tStoreIndicators.setPlaceOrderNumber(Strings.isBlank(item.getPlaceOrderNumber().replace(",",""))?null:Integer.valueOf(item.getPlaceOrderNumber().replace(",","")));
                tStoreIndicators.setHaveVisitGoodsNumber(Strings.isBlank(item.getHaveVisitGoodsNumber().replace(",",""))?null:Integer.valueOf(item.getHaveVisitGoodsNumber().replace(",","")));
                tStoreIndicators.setCustomerOrderPrice(Strings.isBlank(item.getCustomerOrderPrice().replace(",",""))?null:new BigDecimal(item.getCustomerOrderPrice().replace(",","")));

                tStoreIndicators.setCreateTime(new Date());
                tStoreIndicators.setCreateBy(username);

                statDateList.add(tStoreIndicators.getStatDate());
                saveList.add(tStoreIndicators);
            });
            //批量删除旧数据
            tStoreIndicatorsService.deleteOldData(storeId,statDateList);
            //批量插入
            tStoreIndicatorsService.saveBatch(saveList);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        return AjaxResult.success();
    }
}
